import { CommonModal } from "@/views/components/CommonModal";
import { CommonField } from "@/pages/OrderModule/common/components/CommonForm";
import { Button, Col, Form, Row, Popconfirm, Image, InputNumber, Switch, Tabs, Collapse, Radio, Steps, message } from "antd";
import { Input, CommonInput } from "@/views/components/PrefixPlaceholder";
import { useState, useRef, useEffect, useCallback } from "react";
import { NumText } from "@/pages/OrderModule/common/components/CommonText";
import { CommonTable } from "@/pages/OrderModule/common/components/CommonTable";
import CommonImgsLoad from "@/components/CommonImgsLoad";
import { SPU_STATUS } from "@/views/utils/constant";
import GoodsListModal from "./GoodsListModal";
import CombPreviewPage from "./CombPreviewPage";
import Style from "./index.module.less";
import { useLocation } from "react-router-dom";
import { useArchorList } from "./archorList";
import { RightOutlined, DoubleLeftOutlined } from "@ant-design/icons";
import { useAnchor } from "@/pages/OrderModule/common/hooks/useAnchor";
import { cloneDeep, set } from "lodash";
const ARCHOR_LIST_MAP = {
	basicInformation: 0, // 基础信息
	attributes: 1 // 商品属性
	// otherSettings: 2 // 其他设置
};
const BatchModifyProducts = ({ handleOk, onCancel }) => {
	const [visible, setVisible] = useState(0);
	const [searchList, setSearchList] = useState([]);
	const [goodsList, setGoodsList] = useState([]);
	const [mergedList, setMergedList] = useState([]);
	const [specsList, setSpecsList] = useState(0);
	const [search, setSearch] = useState([]);
	const [sonGoodsList, setSonGooodsList] = useState([]);
	const [selectName, setSelectName] = useState("");
	const [records, setRecords] = useState("");
	const [len, setLen] = useState(0);

	const [form] = Form.useForm();

	const goodsImage = form.getFieldValue("image");
	const [isOpen, setOpen] = useState(false);
	const location = useLocation();
	const modalProps = {
		parentForm: form,
		visible,
		specsList,
		selectName,
		records,
		isOpen,
		goodsList,
		searchList,
		isNotShow: true,
		sonGoodsList,
		handleOk() {},
		handleCancelAll() {
			onCancel();
		},
		handleCancel() {
			setVisible(0);
		}
	};
	const CombPreviewModalProps = modalProps;
	const GoodsListModalProps = modalProps;

	const columns = [
		{
			title: "图片",
			dataIndex: "image",
			render: (value, record, i) => <Image width={60} src={value} />
		},
		{
			title: "商品名称",
			dataIndex: "skuName"
		},
		{
			title: "规格",
			dataIndex: "colour",
			render: (text, record, index) => (
				<div>
					<div style={{ marginRight: "10px" }}>
						{record.colour ? [...new Set(record.colour.split(",").map(colour => colour.replace(/\s/g, "")))].length : 0}个颜色
					</div>
					<div style={{ marginRight: "10px" }}>
						{record.specs ? [...new Set(record.specs.split(",").map(specs => specs.replace(/\s/g, "")))].length : 0}尺码
					</div>
				</div>
			)
		},
		{
			title: "规格数",
			dataIndex: "skuCode",
			render: (text, record, index) => (
				<div style={{ display: "flex" }}>
					<div style={{ marginRight: "10px" }}>
						{/* {record.skuCode ? record.skuCode.split(",").length : 0} */}
						{record.skuCode ? record.skuCode.split(",").length : 0}
					</div>
					<span
						className="opera-span-common"
						onClick={() => {
							visibleGoodsListModalAndSelected("search", record);
						}}
					>
						<span className="common-color2">查看</span>
					</span>
				</div>
			)
		},
		{
			title: "零售价(元)",
			dataIndex: "retailPrice",
			render: value => value && <NumText as="s1" pre="¥" num={(value && value != "NaN") || !isNaN(value) ? value : 0} />
		},
		{
			title: "成本价(元)",
			dataIndex: "costPrice",
			render: value => value && <NumText as="s1" pre="¥" num={value && value != "NaN" && !isNaN(value) ? value : 0} />
		},
		{
			title: "市场价(元)",
			dataIndex: "tagPrice",
			render: value => value && <NumText as="s1" pre="¥" num={value && value != "NaN" && !isNaN(value) ? value : 0} />
		},
		{
			title: "采购价(元)",
			dataIndex: "purchasePrice",
			render: value => value && <NumText as="s1" pre="¥" num={value && value != "NaN" && !isNaN(value) ? value : 0} />
		},
		{
			title: "重量(kg)",
			dataIndex: "weight",
			render: value => value && <NumText as="s1" suffix="kg" num={value} />
		},
		{
			title: "数量(个)",
			dataIndex: "num",
			render: (text, record, index) => (
				<div>
					<InputNumber
						defaultValue={1}
						min={1}
						value={text}
						precision={0}
						onBlur={e => handleNumChange(e, record, index)}
						onChange={e => handleNumChange(e, record, index)}
						controls={false}
					/>
				</div>
			)
		},
		{
			title: "操作",
			dataIndex: "index",
			lock: true,
			render: (t, r, i) => (
				<span className="opera-span-common">
					<a style={{ marginRight: "10px" }} onClick={() => visibleGoodsListModalAndSelected("update", r)}>
						编辑
					</a>
					<Popconfirm title="确定删除该条数据?" onConfirm={() => confirm(r)} onCancel={cancel}>
						<a href="#">删除</a>
					</Popconfirm>
				</span>
			),
			width: 100
		}
	];
	// 图片上传失败
	const handleError = (err, failed) => {
		if (!err.isLt2M) {
			Modal.error({ content: "图片仅限1m以内，上传失败", centered: true });
		}
	};
	const computeLen = value => {
		let specsList = [];
		let len = [];
		let lenList = [];
		if (isOpen) {
			value.forEach(i => {
				if (i.specs) {
					specsList = [...specsList, [...new Set(i.specs.split(",").map(specs => specs.replace(/\s/g, "")))]];
				}
			});
			let flattenedArray = specsList.flat();

			setSpecsList(value.length > 0 ? flattenedArray : []);
		} else {
			value.forEach(i => {
				if (i.skuCode) {
					len.push(i.skuCode.split(",").length);
					lenList.push(i);
				}
			});
			const groupedBySkucode = searchList.reduce((groups, obj) => {
				if (!groups[obj.spuCode]) {
					groups[obj.spuCode] = [];
				}
				groups[obj.spuCode].push(obj);
				return groups;
			}, {});
			const result = Object.values(groupedBySkucode);
			specsList = combineArrays(result);
			let product = len.reduce((acc, val) => acc * val, 1);
			setLen(len.length > 0 ? product : 0);
			setSpecsList(value.length > 0 ? specsList : []);
		}
	};
	function combineArrays(arrays) {
		function combine(currentCombination, remainingArrays) {
			if (remainingArrays.length === 0) {
				return [currentCombination];
			}

			const [firstArray, ...restArrays] = remainingArrays;

			return firstArray.reduce((results, currentValue) => {
				return results.concat(combine([...currentCombination, currentValue], restArrays));
			}, []);
		}

		return combine([], arrays);
	}
	useEffect(() => {
		// if (isOpen) {
		const mergedData = searchList.reduce((acc, curr) => {
			const foundItem = acc.find(item => item.spuId === curr.spuId);
			if (foundItem) {
				foundItem.specs += `, ${curr.specs}`;
				foundItem.colorSpecifications += `, ${curr.colorSpecifications}`;
				foundItem.retailPrice += curr.retailPrice ? curr.retailPrice : 0;
				foundItem.costPrice += curr.costPrice ? curr.costPrice : 0;
				foundItem.purchasePrice += !isNaN(curr.purchasePrice) && curr.purchasePrice ? curr.purchasePrice : 0;
				foundItem.weight += curr.weight ? curr.weight : 0;
				foundItem.skuCode += `,${curr.skuCode}`;
				foundItem.productIngredients += `, ${curr.productIngredients}`;
				foundItem.colour += `, ${curr.colour}`;
				foundItem.retailPrice = isNaN(foundItem.retailPrice) ? 0 : foundItem.retailPrice;
				foundItem.weight = isNaN(foundItem.weight) ? 0 : foundItem.weight;
				foundItem.costPrice = isNaN(foundItem.costPrice) ? 0 : foundItem.costPrice;
				foundItem.purchasePrice = isNaN(foundItem.purchasePrice) ? 0 : foundItem.purchasePrice;
			} else {
				acc.push({ ...curr });
			}
			return acc;
		}, []);
		computeLen(mergedData);
		setMergedList(mergedData);
		setGoodsList(mergedData);
		setSonGooodsList(searchList);

		// 图片：不上传，取第一个子商品图片
		if (!goodsImage && searchList.length) {
			form.setFieldsValue({
				image: searchList[0].image
			});
		}
	}, [searchList]);

	const updateData = value => {};

	const onGoodsSkuListSelected = selectedList => {
		if (records) {
			const arr = cloneDeep(searchList);
			const newArr = arr.filter(e => {
				return e.spuId !== records.spuId;
			});
			let uniqueArray = [...cloneDeep(newArr), ...selectedList].filter((item, index) => {
				return [...cloneDeep(newArr), ...selectedList].findIndex(otherItem => otherItem.id === item.id) === index;
			});
			setSearchList(uniqueArray);
		} else {
			let uniqueArray = [...searchList, ...selectedList].filter((item, index) => {
				return [...searchList, ...selectedList].findIndex(otherItem => otherItem.id === item.id) === index;
			});
			setSearchList(uniqueArray);
		}
	};

	/**
	 * 修改源数据
	 */
	const handleNumChange = useCallback(
		(e, record, index) => {
			const val = typeof e === "number" ? e : e ? e.target.value : 1;
			const reg = /^[1-9]\d*$/;
			if (reg.test(val)) {
				const arr = cloneDeep(searchList);

				const newArr = arr.map(e => {
					// if (isOpen) {
					if (e.spuId === record.spuId) {
						e.num = val;
					}
					// } else {
					// 	if (e.skuCode === record.skuCode) {
					// 		e.num = val;
					// 	}
					// }

					return e;
				});
				setSearchList(cloneDeep(newArr));
			} else {
				message.info("请输入正整数");
			}
		},
		[searchList, isOpen]
	);
	// 删除子商品
	const confirm = async record => {
		const arr = cloneDeep(searchList);
		const newArr = arr.filter(e => {
			// if (isOpen) {
			return e.spuId !== record.spuId;
			// } else {
			// 	return e.skuCode !== record.skuCode;
			// }
		});
		setSearchList(cloneDeep(newArr));
		message.success("删除操作成功");
	};
	// 同一商品下同尺码组合
	const onOpenChange = e => {
		setOpen(e);
		setGoodsList([]);
		setSearchList([]);
		setSpecsList([]);
		// if (e) {
		// 	setGoodsList(mergedList);
		// 	computeLen(mergedList);
		// } else {
		// 	setGoodsList(searchList);
		// 	setSpecsList(searchList.length);
		// }
	};
	// 下一步
	function handleOk() {
		if (goodsList.length > 0) {
			setVisible(2);
		} else {
			message.error("未选择商品");
		}
	}

	// 锚点
	const archorList = useArchorList();
	const [tab, setTab] = useState(archorList[ARCHOR_LIST_MAP.basicInformation].key);
	const contentWrapperRef = useRef(null);
	const anchorItems = useRef({});
	const { currentAnchor, scrollToAnchor } = useAnchor(contentWrapperRef, anchorItems);
	useEffect(() => {
		if (currentAnchor) {
			setTab(currentAnchor);
		}
	}, [currentAnchor]);
	useEffect(() => {
		archorList.forEach(item => {
			anchorItems.current[item.key] = document.getElementById(item.key);
		});
	}, []);
	useEffect(() => {}, [goodsList]);

	const cancel = () => {};
	const handleUploadImg = val => {
		form.setFieldsValue({
			image: val
		});
	};
	useEffect(() => {
		if (location.state?.type) {
			setCurrent(0);
			setGoodsList([]);
			setSpecsList([]);
			setLen(0);
			form.resetFields();
		}
	}, [location.state?.type]);
	const RefGoodsListModal = useRef();
	const visibleGoodsListModalAndSelected = (name, r, ids) => {
		setSelectName(name);
		setRecords(r);
		setSearch(goodsList);

		// 回显的ids
		if (!ids) {
			ids = [r.id];
		}

		// visible异步后，才能执回显
		Promise.resolve()
			.then(() => {
				setVisible(1);
			})
			.then(() => {
				setTimeout(() => {
					RefGoodsListModal?.current?.commonPressEnter(`${r.skuCode}*${r.num || 1}`);
				}, 500);
			});
	};
	const steps = [
		{
			title: "批量新增组合商品",
			content: "批量新增组合商品"
		},
		{
			title: "组合预览",
			content: "组合预览"
		}
	];
	const [current, setCurrent] = useState(0);

	const next = () => {
		if (form.getFieldValue("skuCode") === undefined) return message.error("请输入组合编码");
		if (specsList.length === 0) return message.error("请选择商品");
		setCurrent(current + 1);
	};

	const prev = () => {
		setCurrent(current - 1);
	};
	const items = steps.map(item => ({ key: item.title, title: item.title }));
	return (
		<div style={{ background: "#fff", padding: 20 }}>
			<Steps current={current} items={items} />
			<div className={Style.fs18} style={{ fontWeight: 700 }}>
				<span className="mr10">组合商品</span>
				<RightOutlined className="mr10" />
				<span className="mr10" style={{ color: current == 0 ? "rgba(0, 104, 255, 1)" : "" }}>
					批量新增组合商品
				</span>
				{current > 0 && (
					<span>
						<RightOutlined className="mr10" />
						<span className="mr10" style={{ color: "rgba(0, 104, 255, 1)" }}>
							组合预览
						</span>
					</span>
				)}
			</div>
			<div className="steps-action">
				{current == 0 && (
					<span>
						<div className={Style.archor_tab + " rule-reset"}>
							<Tabs
								activeKey={tab}
								onChange={val => {
									if (val === "gototop") {
										val = archorList[ARCHOR_LIST_MAP.basicInformation].key;
									}
									setTab(val);
									scrollToAnchor(val);
								}}
							>
								{archorList.map(item => (
									<Tabs.TabPane tab={item.title == "其他设置" ? "" : item.title} key={item.key}></Tabs.TabPane>
								))}
							</Tabs>
						</div>
						<div className={Style.detail_inner2} ref={contentWrapperRef}>
							<Form form={form}>
								<Collapse
									defaultActiveKey={Object.keys(ARCHOR_LIST_MAP)}
									ghost
									expandIcon={({ isActive }) => (
										<DoubleLeftOutlined rotate={isActive ? 270 : 90} style={{ fontSize: "16px", color: "#4E5969" }} />
									)}
									expandIconPosition="end"
									className={Style["reset-collapse"]}
								>
									<>
										<Collapse.Panel header={archorList[ARCHOR_LIST_MAP.basicInformation].render()} key="basicInformation">
											<Row gutter={[12, 6]} id="basic-data">
												<Col span={12}>
													<Form.Item name="skuName">
														<CommonField Component={Input} placeholder="请输入组合商品名称" showCount maxLength={100} />
													</Form.Item>
												</Col>
												<Col span={6}>
													<Row>
														<Col span={22}>
															<Form.Item name="skuCode" rules={[{ required: true, message: "请输入组合编码" }]}>
																<CommonInput
																	Component={Input}
																	placeholder="请输入组合编码"
																	aria-required
																	showCount
																	maxLength={200}
																/>
															</Form.Item>
														</Col>
													</Row>
												</Col>
												<Col span={24}>
													{/* 不上传，取第一个子商品图片 */}
													{/* style={{ borderTop: 'none', borderLeft: 'none', borderRight: 'none' }} */}
													<div style={{ marginBottom: 10 }}>组合商品图片</div>
													<Form.Item label="" name="image">
														<div style={{ display: "flex" }}>
															<div>
																<CommonImgsLoad
																	img={goodsImage}
																	handleOk={handleUploadImg}
																	handleError={handleError}
																	upLoadText="请上传"
																/>
															</div>
															<div className="ml8" style={{ color: "rgba(177, 183, 195, 1)" }}>
																图片建议与第三方平台保存一致
															</div>
														</div>
													</Form.Item>
												</Col>
											</Row>
										</Collapse.Panel>

										<Collapse.Panel header={archorList[ARCHOR_LIST_MAP.attributes].render()} key="attributes">
											<Row gutter={[12, 6]} className="mb20">
												<Col span={4}>
													同一商品下同尺码组合：
													<Switch checked={isOpen} onClick={e => onOpenChange(e)} size="default" />
												</Col>
												<Col span={4}>
													<div>当前可成组合数：{isOpen ? specsList.length : len}</div>
												</Col>
											</Row>

											<Row gutter={[12, 6]}>
												<Col span={4}>
													<Button
														type="primary"
														style={{ marginRight: "8px" }}
														onClick={() => {
															setVisible(1), setSelectName("add"), setRecords("");
														}}
													>
														新增商品
													</Button>
												</Col>

												<CommonTable
													rowKey="key"
													scroll={{ y: `calc(100vh - 250px)` }}
													columns={columns}
													dataSource={goodsList}
													pagination={false}
												/>
											</Row>
										</Collapse.Panel>
										{/* {false && (
											<Collapse.Panel
												header={archorList[ARCHOR_LIST_MAP.otherSettings].render()}
												key="otherSettings"
											></Collapse.Panel>
										)} */}
									</>
								</Collapse>
							</Form>
						</div>
						{visible == 1 && (
							<GoodsListModal
								ref={RefGoodsListModal}
								onGoodsSkuListSelected={onGoodsSkuListSelected}
								updateData={updateData}
								{...GoodsListModalProps}
							/>
						)}
						<Button type="primary" size="middle" className={Style.fixedRight1} onClick={() => next()}>
							下一步
						</Button>
					</span>
				)}
				{current > 0 && (
					<span>
						<CombPreviewPage {...CombPreviewModalProps} />
						<Button size="middle" className={Style.fixedRight1} onClick={() => prev()}>
							上一步
						</Button>
					</span>
				)}
			</div>
		</div>
	);
};

export default BatchModifyProducts;
